package com.yxsk.relay.job.admin.core.router.callback;

import com.yxsk.relay.job.admin.core.router.container.EndpointCycleList;
import com.yxsk.relay.job.admin.core.router.endpoint.SimpleEndpointRouterInfo;
import com.yxsk.relay.job.component.admin.registry.callback.SlaveChangeCallback;
import com.yxsk.relay.job.component.common.vo.Endpoint;
import com.yxsk.relay.job.component.common.vo.SlaveInfo;
import lombok.AllArgsConstructor;

import java.util.Map;

/**
 * @Author 11376
 * @CreaTime 2019/6/15 12:00
 * @Description
 */
@AllArgsConstructor
public class StewardCallback implements SlaveChangeCallback {

    // key: appName, value: endpoint list
    private Map<String, EndpointCycleList> endpointInfoMap;

    @Override
    public void online(SlaveInfo slaveInfo) {
        if (endpointInfoMap != null) {
            EndpointCycleList endpointList = this.endpointInfoMap.get(slaveInfo.getAppName());
            if (endpointList == null) {
                endpointList = new EndpointCycleList();
            }
            SimpleEndpointRouterInfo endpointRouterInfo = new SimpleEndpointRouterInfo();

            Endpoint endpoint = new Endpoint();
            endpoint.setHost(slaveInfo.getEndpoint().getHost());
            endpoint.setPort(slaveInfo.getEndpoint().getPort());
            endpoint.setAuthToken(slaveInfo.getEndpoint().getAuthToken());
            endpoint.setProtocol(slaveInfo.getEndpoint().getProtocol());

            endpointRouterInfo.setEndpoint(endpoint);

            endpointList.addEndpoint(endpointRouterInfo);

            this.endpointInfoMap.put(slaveInfo.getAppName(), endpointList);
        }
    }

    @Override
    public void offline(SlaveInfo slaveInfo) {
        if (endpointInfoMap != null) {
            EndpointCycleList endpointList = this.endpointInfoMap.get(slaveInfo.getAppName());
            if (endpointList != null) {
                endpointList.remove(slaveInfo.getEndpoint().getHost(), slaveInfo.getEndpoint().getPort());
            }
        }
    }

}
